package org.bangumibuddy.parser.impl;

import lombok.SneakyThrows;
import org.bangumibuddy.parser.AnimeMetaParser;
import org.bangumibuddy.parser.factory.AnimeMetaParserFactory;
import org.bangumibuddy.pojo.TorrentFile;
import org.bangumibuddy.pojo.anime.Anime;
import org.bangumibuddy.pojo.anime.AnimeMetaData;
import org.bangumibuddy.pojo.anime.AnimeSummary;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MikanRssParser extends DefaultRssParser {

    final String MIKAN_RSS = "http://mikanani.me/RSS";
    final String MIKAN_BANGUMI = "http://mikanani.me/Home/Bangumi/";
    final String MIKAN = "http://mikanani.me/";
    final String POSTERWIDTH="width=400";
    final String POSTERHEIGHT="height=560";
    final String POSTERFORMAT="format=jpg";

    private String Poster;
    private String Season;

    private Integer SeasonNumber;

    private String Year;
    boolean isInit = false;

    public MikanRssParser(File rssfile) {
        super(rssfile);
        CheckMikanRss();
    }

    public MikanRssParser(String url) {
        super(url);
        CheckMikanRss();
    }

    private boolean CheckMikanRss() {
         if(!feed.getLink().contains(MIKAN_RSS))
                throw new RuntimeException("rss file is not mikan rss");

         return true;
    }

    @Override
    public Integer getSeasonNumber() {
        Init();
        return SeasonNumber;
    }

    @Override
    @SneakyThrows
    public String getPoster() {
        Init();
        return Poster;
    }

    @Override
    public String getYear(){
        Init();
        return Year;
    }

    @Override
    public String getTitle() {
        // Create a regex pattern
        Pattern pattern = Pattern.compile("Mikan Project\\s*-\\s*(.*?)\\s*(第.*季)?");

        // Create a matcher
        Matcher matcher = pattern.matcher(feed.getTitle());

        // Find the match
        if (matcher.find()) {
            if(feed.getTitle().contains("第")){
                return feed.getTitle().
                        substring(
                                feed.getTitle().indexOf("-")+1,
                                feed.getTitle().indexOf("第")).
                        trim();
            }else {
                return feed.getTitle().substring(feed.getTitle().indexOf("-") + 1).trim();
            }
        }

        return feed.getTitle();
    }

    @SneakyThrows
    private void Init(){
        if (isInit) return;

        String bangumiId = GetBangnumiId();
        URL url = new URL(MIKAN_BANGUMI + bangumiId);

        // Connect to the URL and get the HTML
        Document document = Jsoup.connect(url.toString()).get();
        InitPoster(document);
        InitSeason(document);
        InitYear(document);

        isInit = true;
    }

    private void InitYear(Document document){
        Elements title = document.select("p.bangumi-info");
        for (Element element : title) {
            // Create a regex pattern
            Pattern pattern = Pattern.compile("(\\d+)/(\\d+)/(\\d+)");

            // Create a matcher
            Matcher matcher = pattern.matcher(element.text());
            if(matcher.find()){ //match xx/xx/xxxx
                Year = matcher.group(3);
            }
        }
    }

    private void InitSeason(Document document){
        Elements title = document.select("p.bangumi-title");

        if (title.text().contains("第"))
        {
            Season = title.text().substring(title.text().indexOf("第")).trim();
            InitSeasonNumberFromSeason(Season);
        }
        else
        {
            Season = "第一季";
            SeasonNumber = 1;
        }
    }

    private void InitSeasonNumberFromSeason(String season)
    {
        String[] patterns = {"第一季", "第二季", "第三季", "第四季", "第五季", "第六季", "第七季", "第八季", "第九季", "第十季"};
        for (int i = 0; i < patterns.length; i++)
        {
            if (season.contains(patterns[i]))
            {
                SeasonNumber = i + 1;
                break;
            }
        }
    }

    private void InitPoster(Document document)
    {
        // Select the poster element
        Element posterElement = document.select("div.bangumi-poster").first();

        // Get the style attribute of the poster element
        String style = posterElement.attr("style");

        // Extract the URL from the style attribute
        Pattern pattern = Pattern.compile("url\\((.*?)\\)");
        Matcher matcher = pattern.matcher(style);
        if (matcher.find()) {
            String posterUrl = matcher.group(1);

            // Get the substring from the beginning of the string to the position of ".jpg"
            String imgURL = posterUrl.substring(0, posterUrl.indexOf(".jpg") + 4).substring(2);

            Poster= MIKAN + imgURL + "?" + POSTERWIDTH + "&" + POSTERHEIGHT + "&" + POSTERFORMAT;
        }else
            Poster = "";
    }


    @Override
    public String getSeason() {
        Init();
        return Season;
    }

    @SneakyThrows
    private String GetBangnumiId(){
        // Step 1: Create a URL object
        URL url = new URL(feed.getLink());

        // Step 2: Get the query string
        String query = url.getQuery();

        // Step 3: Split the query string into parameters
        String[] params = query.split("&");

        for (String param : params) {
            // Step 4: Split the parameter into name and value
            String[] nameValue = param.split("=");

            // Step 5: Check if the parameter name is "bangumiId"
            if (nameValue[0].equals("bangumiId")) {
                return nameValue[1];
            }
        }

        return "";
    }
}
